from multiprocessing import Process
from flask import request
from httpserver.json_flask import JsonFlask
from httpserver.json_response import JsonResponse
from tess_local_simulator.main import start_local_tess_simulator
app = JsonFlask(__name__)
# 添加车辆数
platoon = 0
vehicleNum = 0
vehiclePoints = None
status = None

PENDING = 'pending'
SUCCESS = 'success'
ERROR = 'error'

process_car_dict = {}

process_dist = {}


@app.route('/jd/startTessng', methods=['Post'])
def startLocalSimulator():
    '''
        启动仿真
    '''
    global process_dist
    # 获取仿真配置
    sim_cfg = request.get_json()
    config_dict = {}
    config_dict['netPath'] = r'net_file\浙江大桥二期.tess'
    config_dict['proj'] = '+proj=tmerc +lat_0=28.2105 +lon_0=121.2455 +k=1 +x_0=0 +y_0=0 +datum=WGS84'
    tess_process = Process(target=start_local_tess_simulator, args=(config_dict,))
    tess_process.start()
    # process_dist[key] = tess_process
    return JsonResponse.success("仿真程序启动成功","success")


@app.route('/jd/stopTessng', methods=['Post'])
def stopSimulator():
    '''
        启动仿真
    '''
    global process_dist
    # 获取仿真配置
    sim_cfg = request.get_json()
    print("结束参数：", sim_cfg)
    key = sim_cfg['dataChannel']
    if key not in process_dist.keys():
        return JsonResponse.success_with_msg('该测试任务未运行')
    task_process = process_dist.get(key)
    process_dist.pop(key)
    task_process.terminate()
    task_process.join()
    return JsonResponse.success_with_msg('仿真停止成功')


@app.errorhandler(Exception)
def error_handler(e):
    """
    全局异常捕获
    """
    return JsonResponse.error(msg=str(e))


def runstart():
    app.run(host='0.0.0.0', port=5003)


def httpserver():
    runstart()
